const { Client } = require("ssh2");

const config = global.config.server;
const executeSSHCommand = (command, callback) => {
  const conn = new Client();
  conn
    .on("ready", () => {
      console.log("成功链接" + config.host + "库");
      conn.exec(command, (err, stream) => {
        if (err) {
          console.error("Error executing command:", err);
          conn.end();
          callback(err, null);
          return;
        }
        let output = "";
        stream.stdin.write("Aa2317770710\n");
        stream.on("data", (data) => {
          output += data.toString();
        });
        stream.on("end", () => {});
        stream.stderr.on("data", (data) => {
          callback(new Error("STDERR: " + data), null);
        });
        stream.on("close", (code, signal) => {
          conn.end();
          callback(null, output);
        });
      });
    })
    .on("error", (err) => {
      callback(err, null);
    })
    .connect(config);
};

module.exports = executeSSHCommand;
